package com.mindata.blockmanager.filter;

import com.mindata.blockmanager.utils.RequestThreadLocal;
import com.mindata.blockmanager.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * User: jasperxgwang
 * Date: 2018-7-12 14:26
 */
@WebFilter(urlPatterns = "/*")
@Slf4j(topic = "PrintRequestFilter")
public class PrintRequestFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info(">>>>>>PrintRequestFilter init");

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request2 = (HttpServletRequest) request;
        String uri = request2.getRequestURI();
        if (!StringUtils.endsWith(uri, ".js") && !StringUtils.endsWith(uri, ".css") && !StringUtils.endsWith(uri, ".png")) {
            String ip = request2.getHeader("X-Real-IP");
            ip = StringUtils.defaultIfEmpty(ip, "127.0.0.1");
            log.info(request2.getRequestURI() + "[ip=" + ip + "]");
            RequestThreadLocal.set(request2.getRequestURI());
            RequestUtil.printAll(request, this, true, null);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
